#!/usr/bin/python
# -*- coding:utf-8 -*-
from pytdx.hq import TdxHq_API
from base_api.singleton import singleton
import datetime
import json


@singleton
class TdxHqTool:
    """ tdx hq api 的说明 """

    def __init__(self):
        self.configs = {}
        self.cur_select_index = None
        self.tdx_server_addr = None
        self.tdx_server_port = None
        self.api = TdxHq_API()

    def connect_server(self):
        api = self.api
        with api.connect(self.tdx_server_addr, self.tdx_server_port):
            file_name = r'output\work_file_' + datetime.datetime.now().strftime('%b_%d_%Y_%H_%M_%S.txt')
            with open(file_name, mode='w') as f:
                data = api.get_security_bars(9, 0, '000001', 0, 10)  # 返回普通list
                print(data)
                f.write(str(data))
                f.write('\n')
                data = api.to_df(api.get_security_bars(9, 0, '000001', 0, 10))  # 返回DataFrame
                print(data)
                f.write(str(data))
                f.write('\n')

    def read_config(self):
        with open(r'config\tdx_trader_server_cfg.json', mode='rb') as file_object:
            json_file_config: dict = json.load(file_object)
            self.configs = {}

        if 'server_select_idx' in json_file_config.keys():
            self.cur_select_index = json_file_config['server_select_idx']
        else:
            self.cur_select_index = 1
            with open(r'config\tdx_trader_server_cfg.json', mode='w') as file_object:
                self._write_cur_select_index(file_object, self.cur_select_index, json_file_config)

        if 'server_config' in json_file_config.keys():
            server_config_arr: list = json_file_config['server_config']
            for config_dict in server_config_arr:
                self.configs[config_dict['index']] = config_dict
            self.tdx_server_addr = self.configs[self.cur_select_index]['server_addr']
            self.tdx_server_port = int(self.configs[self.cur_select_index]['server_port'])
            print('选择连接Sserver ', self.configs[self.cur_select_index]['server_name'])

    @staticmethod
    def _write_cur_select_index(file_object, cur_select_index, json_file_config):
        json_file_config['server_select_idx'] = cur_select_index
        dump_str = json.dumps(json_file_config, indent=4)
        file_object.write(dump_str)


if __name__ == '__main__':
    tdx_hq = TdxHqTool()
    tdx_hq.read_config()
    tdx_hq.connect_server()
    print('exec end.')
